package cn.laixueit.utils;

import cn.hutool.core.date.DateUtil;
import cn.laixueit.mapper.CodeMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author duxiang
 * @date 2023/12/1 16:55
 */

@Component
public class CodeUtils {
    @Resource
    private CodeMapper codeMapper;

    public String getNewCode() {
        String code = codeMapper.getCode("code", "tb_soft");
        if(StringUtils.isNotBlank(code)){
            String pre = code.substring(0,8);
            String end = code.substring(8);
            AtomicInteger atomicInteger = new AtomicInteger(Integer.valueOf(end));
            atomicInteger.getAndIncrement();
            code = String.format(pre + "%03d", atomicInteger.get());
        }else{
            LocalDateTime dateTime = LocalDateTime.now(ZoneId.systemDefault());
            String str = DateUtil.format(dateTime, "yyyyMMdd");
            code = String.format(str + "%03d", 1);
        }
        return code;
    }

    public String getNewCode(String fieldName,String tableName) {
        String code = codeMapper.getCode(fieldName, tableName);
        if(StringUtils.isNotBlank(code)){
            String pre = code.substring(0,8);
            String end = code.substring(8);
            AtomicInteger atomicInteger = new AtomicInteger(Integer.valueOf(end));
            atomicInteger.getAndIncrement();
            code = String.format(pre + "%03d", atomicInteger.get());
        }else{
            LocalDateTime dateTime = LocalDateTime.now(ZoneId.systemDefault());
            String str = DateUtil.format(dateTime, "yyyyMMdd");
            code = String.format(str + "%03d", 1);
        }
        return code;
    }
}
